Java類別Stack
method | |
---|---|
1 | boolean empty() 判斷向量是否為空向量。 |
2 | Object peek( )反饋向量中最頂部(最後放入)的物件。 |
3 | Object pop( )移除並返饋向量中最頂部(最後放入)的物件。 |
4 | Object push(Object element)新增物件至向量中。 |
連結:https://leetcode.com/problems/baseball-game/description/
class Solution {
public int calPoints(String[] operations) {
Stack<Integer> save = new Stack<Integer>();
for (int i = 0; i < operations.length;i++)
{
String s = operations[i];
if (s.equals("C"))
{
save.pop();
}
else if (s.equals("+"))
{
int first = save.pop();
int second = save.peek();
save.push(first);
save.push(first + second);
}
else if (s.equals("D"))
{
int first = save.peek();
save.push(first * 2);
}
else
{
save.push(Integer.parseInt(s));
}
}
int sumofStack=0;
while(!save.isEmpty()){
sumofStack = sumofStack + save.pop();
}
return sumofStack;
}
}
連結:https://leetcode.com/problems/simplify-path/description/
class Solution {
public String simplifyPath(String path) {
Stack<String> save = new Stack<String>();
String arr[] = path.split("/");
for(int i=0;i<arr.length;i++){
if(arr[i].isEmpty())//雙//忽略
{
continue;
}
if(arr[i].equals("..") && !save.empty())//上一層
{
save.pop();
}
else if(!arr[i].equals("..") && !arr[i].equals("."))
{
save.push(arr[i]);//路徑紀錄
}
}
if(save.isEmpty()){
return "/";
}
StringBuilder sb = new StringBuilder();
while (!save.isEmpty())
{
sb.insert(0,save.pop());
sb.insert(0,"/");
}
return sb.toString();
}
}